package rmi;

import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import toolkit.Debug;
import toolkit.Global;

public class Client
{
	public Registry registry;

	public static final int EXPORT_PORT = 2006;
	
	public Client(String serverCodebase, int registryPort) throws RemoteException
	{
		System.setProperty("java.security.policy", Global.getUserDir() + "/src/poker.policy");
		
		System.setProperty("java.rmi.server.codebase", "http://mcemperor.nl/projectpoker/client/projectpoker-client.jar http://mcemperor.nl/projectpoker/server/projectpoker-server.jar");
		//System.setProperty("java.rmi.server.codebase", "http://mcemperor.nl/projectpoker/client/projectpoker-client.jar" + " " + "http://mcemperor.nl/projectpoker/server/projectpoker-server.jar");
		
		System.setSecurityManager(new RMISecurityManager());
		
		registry = LocateRegistry.getRegistry(registryPort);
	}
	
	public static Remote toStub(Remote remoteObject) throws RemoteException
	{
		return toStub(remoteObject, EXPORT_PORT);
	}
	
	public static Remote toStub(Remote remoteObject, int port) throws RemoteException
	{
		try
		{
			return UnicastRemoteObject.exportObject(remoteObject, port);
		}
		catch (RemoteException e)
		{
			if (Debug.isEnabled())
			{
				port += 1;
				
				return toStub(remoteObject, port);
			}
			else
			{
				throw e;
			}
		}
	}
	
	public Object getServerObject(String key) throws RemoteException, NotBoundException
	{
		Object serverObject = null;
		
		if (registry != null)
		{
			serverObject = registry.lookup(key);
		}
		
		return serverObject;
	}
}
